<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        v-model="value1"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :upload-error="uploadError"
        :upload-after='uploadAfter'
        :before-close="beforeClose"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot-scope="{ row, index }" slot="isShow">
          <el-switch
            v-if="row.uid == -1"
            v-model="row.isShow"
            :active-value="1"
            :inactive-value="2"
            @change="listenStatus(row, index)"
          >
          </el-switch>
        </template>
        <template slot-scope="{ row, index }" slot="isCopy">
          <el-switch
            v-if="row.dynamicType == 1"
            v-model="row.isCopy"
            :active-value="1"
            :inactive-value="2"
            @change="listenStatus1(row, index)"
          >
          </el-switch>
        </template>
<!--        <template slot-scope="{ type, size, row }" slot="menu">-->
<!--          <el-button-->
<!--            v-if="row.type === 1"-->
<!--            icon="el-icon-view"-->
<!--            :size="size"-->
<!--            :type="type"-->
<!--            @click="goscoreset(row)"-->
<!--            >学习统计</el-button-->
<!--          >-->
<!--        </template>-->
      </avue-crud>
    </basic-container>


    <el-drawer
      :visible.sync="dialogPermissionVisible"
      :close-on-click-modal="false"
      title="查看统计"
      :size="1000"
    >
      <div class="dialog-setscore" style="padding: 10px">
        <el-row style="margin-bottom: 20px">
          <div style="margin-bottom: 20px;font-size:15px;">
            文章名称:{{ tableData2.dynamicName }}
          </div>
          <span style="margin-bottom: 20px;font-size:15px;"
            >文章阅读情况:必看人数:{{ tableData2.isseeNum }}，有{{
              tableData2.finishNum
            }}人完成，{{ tableData2.unfinishNum }}人未完成</span
          >
          <el-button style="float: right" @click="dialogVisible = true">
            一键通知
          </el-button>
        </el-row>
        <avue-crud
          ref="crud2"
          :page="page1"
          :data="tableData1"
          :permission="permissionList"
          :table-loading="tableLoading"
          :option="tableOption1"
          :search.sync="searchForm1"
          @on-load="getList1"
          @search-change="searchChange1"
          @refresh-change="refreshChange1"
          @size-change="sizeChange1"
          @current-change="currentChange1"
          @row-update="handleUpdate1"
          @row-save="handleSave1"
          @row-del="rowDel1"
        >
        </avue-crud>
      </div>
    </el-drawer>
    <el-dialog
      title="通知提示"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <template>
        <div class="execution">
          <basic-container>
            <avue-form
              ref="form1"
              :option="tableOption2"
              v-model="form1"
              @submit="submit"
            >
            </avue-form>
          </basic-container>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  changeStatus,
  changeStatus1,
  getUserList,
  addObj2
} from "@/api/circledynamic";
import { fetchList1, getObj1, addObj1, putObj1, delObj1 } from '@/api/dynamicviews'
import { tableOption, tableOption1, tableOption2, tableOption3 } from "@/const/crud/circledynamic";
import { mapGetters } from "vuex";
import AvueUeditor from 'avue-plugin-ueditor'

export default {
  name: "circledynamic",
  data() {
    return {
      dialogFlag:false,
      dialogVisible: false,
      form: {
        ids: []
      },
      form1: {
        dynamic: ''
      },

      levelOne: [],
      searchForm: {},
      searchForm1: {
        startTime: [],
        endTime: [],
      },
      tableData: [],
      tableData1: [],
      tableData2: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      page1: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableLoading1: false,
      tableOption: tableOption,
      dialogPermissionVisible: false,
      tableOption1: tableOption1,
      tableOption2: tableOption2,
      dic: [
        {
          label: "",
          value: 2
        },
        {
          label: "",
          value: 1
        }
      ],

      // videoUrl: '',
      // audioUrl: ''
      time: 0,
      value1: {}
    };
  },
  mounted() {
    var radio = this.findObject(this.tableOption.column, 'dynamicType')
    var audio = this.findObject(this.tableOption.column, 'audio')
    radio.change = this.radioChange;
    var video = this.findObject(this.tableOption.column, 'video')
    video.uploadAfter = (res, done, loading, column) => {
      // console.log(res, column);
      // console.log(this.value1)
      this.value1.time = res.ls;
      // this.time = res.ls;
      done();
    };
    audio.uploadAfter = (res, done, loading, column) => {
      console.log(res, column);
      this.value1.time = res.ls;
      // this.time = res.ls;
      done();
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.circleDynamic_circledynamic_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.circleDynamic_circledynamic_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.circleDynamic_circledynamic_edit,
          false
        )
      };
    }
  },
  methods: {
     beforeClose(done,type){
        if(type == "add" || type == "edit"){
            if(this.dialogFlag == true){
                done()
            }
            if(this.dialogFlag == false){
                this.$confirm("可能有未保存的数据，是否关闭", '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(data => {
                    done()
                }).catch(_ => {
                        // done()
                });
            }
        }else{
            done()
        }

    },
    submit(form1, done) {
      form1.dynamic = this.rowid
      var vm = this;
      var noticeArr = form1.way;
      var newNoticeArr = [];
      noticeArr.map(r => {
        newNoticeArr.push(r);
      })
      form1.way = newNoticeArr.join(',');
      addObj2(form1).then(data => {
        this.$message.success('提交成功')
        vm.dialogVisible = false
        done()
      }).catch(() => {

      });
    },
    handleClose(done) {
      done();
    },
    radioChange(val) {
      // console.log(val);
      this.audioList = [];
      var video = this.findObject(this.tableOption.column, 'video')
      var audio = this.findObject(this.tableOption.column, 'audio')
      var introduction = this.findObject(this.tableOption.column, 'introduction')
      var content = this.findObject(this.tableOption.column, 'content')
      var cover = this.findObject(this.tableOption.column, 'cover')
      var time = this.findObject(this.tableOption.column, 'time')
      var isCopy = this.findObject(this.tableOption.column, 'isCopy')
      var largefile = this.findObject(this.tableOption.column,'largefile')
      // console.log(video)
      // console.log(cover)

      var ids = this.findObject(this.tableOption.column, 'ids')
      var type = this.tableData
      type.map(r => {
        if (r.type === 2) {
          ids.display = false
        }
        return r
      })
      if (val.value == 1) {
        video.display = false;
        audio.display = false;
        introduction.display = false;
        content.display = true;
        cover.display = false;
        time.display = true;
        isCopy.display = true;
        largefile.display = false;
        this.value1.video = '';
        this.value1.audio = '';
      }
      if (val.value == 2) {
        video.display = true;
        audio.display = false;
        introduction.display = true;
        content.display = false;
        cover.display = true;
        largefile.display = false;
        time.display = false;
        isCopy.display = false;
        this.value1.audio = '';
      }
      if (val.value == 3) {
        video.display = false;
        audio.display = true;
        introduction.display = true;
        content.display = false;
        cover.display = false;
        largefile.display = false;
        time.display = false;
        isCopy.display = false;
        this.value1.video = '';
      }
      if(val.value == 5){
        video.display = false;
        audio.display = false;
        introduction.display = false;
        content.display = true;
        cover.display = false;
        time.display = false;
        isCopy.display = false;
        largefile.display = true;
        this.value1.video = '';
        this.value1.audio = '';
      }
    },


    uploadError(error, column) {
      console.log(error)
      console.log(column)
      this.$message.error("上传失败");
    },
    uploadAfter(res,done){
      console.log(res)
      // console.log(column)
      done()
    },
    //监听状态切换
    listenStatus(row, index) {
      console.log(row);
      changeStatus(row.id).then(res => {
        console.log(res);
        this.$message.success("操作成功");
      });
    },

    //监听状态切换
    listenStatus1(row, index) {
      console.log(row);
      changeStatus1(row.id).then(res => {
        console.log(res);
        this.$message.success("操作成功");
      });
    },
    getList(page, params) {
      var vm = this;
      axios.get('/circleorganizational/page/list/user').then(res => {
        let circleorganizational = res.data.data.circleOrganizationalVoList
        // console.log(this.circleorganizational)
        circleorganizational && circleorganizational.map(r => {
          vm.levelOne.push(r.id);
        })
        this.tableOption.column.map(r => {
          if (r.prop === 'ids') {
            r.dicData = circleorganizational
          }
          return r;
        })
      })
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          var listData = response.data.data.records;
          listData.map(r => {
            if (!r.ids) {
              r.ids = [];
            } else {
              r.ids = r.ids.split(',');
            }
            return r;
          })
          this.tableData = listData;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function (row, index) {
      this.$confirm("是否确认删除标题为:" + row.title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function (row, index, done, loading) {

      if (typeof (row.video) != 'string') { row.video = '' }
      if (typeof (row.audio) != 'string') { row.audio = '' }
      if (typeof (row.cover) != 'string') { row.cover = '' }
      if (typeof (row.largefile) != 'string') { row.largefile = '' }
      // if (row.dynamicType == 2 || row.dynamicType == 3) {
      //   this.videoUrl = row.video;
      //   this.audioUrl = row.audio;
      //   setTimeout(() => {
      //     var videopl = document.getElementById("video");
      //     var audiopl = document.getElementById("audio");
      //     row.time = row.dynamicType == 2 ? videopl.duration : audiopl.duration;
      //   }, 800)
      // }
      // setTimeout(() => {
      var vm = this;
      if (row.ids) {
        var idsArr = row.ids;
        var newIdsArr = [];
        idsArr.map(r => {
          if (vm.levelOne.indexOf(r) === -1) {
            newIdsArr.push(r);
          }
        })
        console.log(row)
        row.ids = newIdsArr.join(',');
      }

      putObj(row)
        .then(data => {
          vm.dialogFlag = true
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
        setTimeout(()=>{
            vm.dialogFlag = false
        },500)
      // }, 1000)
    },
    handleSave: function (row, done, loading) {
      if (typeof (row.video) != 'string') { row.video = '' }
      if (typeof (row.audio) != 'string') { row.audio = '' }
      if (typeof (row.cover) != 'string') { row.cover = '' }
      if (typeof (row.largefile) != 'string') { row.largefile = '' }
      // if (this.time) {
      //   row.time = this.time;
      //   this.time = 0;
      // }

      // if (row.dynamicType == 2 || row.dynamicType == 3) {
      //   this.videoUrl = row.video;
      //   this.audioUrl = row.audio;
      //   setTimeout(() => {
      //     var videopl = document.getElementById("video");
      //     var audiopl = document.getElementById("audio");
      //     row.time = row.dynamicType == 2 ? videopl.duration : audiopl.duration;
      //   }, 800)
      // }

      var vm = this;
      if (row.ids) {
        var idsArr = row.ids;
        var newIdsArr = [];
        idsArr.map(r => {
          if (vm.levelOne.indexOf(r) === -1) {
            newIdsArr.push(r);
          }
        })
        row.ids = newIdsArr.join(',');
      }


      console.log(row);
      setTimeout(() => {
        addObj(row)
          .then(data => {
            vm.dialogFlag = true
            this.$message.success("添加成功");
            done();
            this.getList(this.page);
          })
          .catch(() => {
            loading();
          });
      }, 500)
      setTimeout(()=>{
        vm.dialogFlag = false
      },500)
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },


    //文章统计
    getList1(page, params) {
      this.tableLoading1 = true
      var params = params ? params : {}
      params.dynamic = this.rowid
      fetchList1(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm1)).then(response => {
        this.tableData1 = response.data.data.circleDynamicViewsPage.records
        this.tableData2 = response.data.data.circleDynamicViewsVo
        this.page1.total = response.data.data.total
        this.tableLoading1 = false
      }).catch(() => {
        this.tableLoading1 = false
      })
    },
    rowDel1: function (row, index) {
      this.$confirm('是否确认删除观看记录：' + row.info, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj1(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList1(this.page1)
      })
    },
    handleUpdate1: function (row, index, done, loading) {
      putObj1(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList1(this.page1)
      }).catch(() => {
        loading();
      });
    },
    handleSave1: function (row, done, loading) {

      var row = row
      console.log(row);
      row.tasktype = this.rowid
      addObj1(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList1(this.page1)
      }).catch(() => {
        loading();
      });
    },
    sizeChange1(pageSize) {
      this.page1.pageSize = pageSize
    },
    currentChange1(current) {
      this.page1.currentPage = current
    },
    searchChange1(form, done) {
      this.searchForm1 = form
      if (this.searchForm1.update_time) {
        var date = this.searchForm1.update_time[0]
        var date1 = this.searchForm1.update_time[1]
        //开始时间处理
        var formatDate = function (date) {
          var y = date.getFullYear();
          var m = date.getMonth() + 1;
          m = m < 10 ? '0' + m : m;
          var d = date.getDate();
          d = d < 10 ? ('0' + d) : d;
          // var h = '00'
          // var minute = '00'
          // var second = '00'
          var h = date.getHours();
          h = h < 10 ? ('0' + h) : h;
          var minute = date.getMinutes();
          var second = date.getSeconds();
          second = second < 10 ? ('0' + second) : second;
          minute = minute < 10 ? ('0' + minute) : minute;
          return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
        };
        //结束时间处理
        var formatDateTime = function (date) {
          var y = date.getFullYear();
          var m = date.getMonth() + 1;
          m = m < 10 ? ('0' + m) : m;
          var d = date.getDate();
          d = d < 10 ? ('0' + d) : d;
          // var h = '23';
          var h = date.getHours();
          h = h < 10 ? ('0' + h) : h;
          // var minute = '59';
          var minute = date.getMinutes();
          minute = minute < 10 ? ('0' + minute) : minute;
          // var second='59';
          var second = date.getSeconds();
          second = second < 10 ? ('0' + second) : second;
          console.log(y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second)
          return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
        };
        this.searchForm1.startTime = formatDate(date)
        this.searchForm1.endTime = formatDateTime(date1)
      }

      this.page1.currentPage = 1
      this.getList1(this.page1, form)
      done()
    },
    refreshChange1() {
      this.getList1(this.page1)
    },
    goscoreset: function (row) {
      this.rowid = row.id
      this.dialogPermissionVisible = true
      var dic = { dynamic: row.id }
      this.getList1(this.page1, dic)
    }

  }
};
</script>
<style lang="scss">
.avue-ueditor__dialog {
  z-index: 9;
}
</style>
